﻿IF OBJECT_ID('up_KML_GpsVisitXmissionStructures') IS not NULL
	DROP PROC up_KML_GpsVisitXmissionStructures 

GO 

CREATE PROCEDURE [dbo].[up_KML_GpsVisitXmissionStructures]
	 @id int 
AS


DECLARE @TransmissionGpsVisitsList varchar(MAX)
SET @TransmissionGpsVisitsList = ''

SELECT 
	 @TransmissionGpsVisitsList = @TransmissionGpsVisitsList + CONVERT(varchar, [Vendor_Visit_XMissionStructures_PoleId]) + ','
FROM 
	v_tb_Vendor_Visit_XMissionStructures_Poles Pole
INNER JOIN v_tb_Vendor_Visit_XMissionStructures Structures
	ON Pole.Vendor_Visit_XMissionStructureFK = Structures.Vendor_Visit_XMissionStructureId
WHERE
	Structures.Vendor_ProjectFK = @id


declare @settingValue varchar(500)
set @settingValue = (select SettingValue from tb_Settings where SettingId = 26)

declare @template varchar(max);
set @template = '
	<iframe 
		src="{url}{page}?ID=$[ID]" 
		style="width: 325px; height: 400px;"
		frameborder="0"  marginwidth="0" marginheight="0">Pole Position</iframe>
		$[description]'
select @template = replace(@template, '{url}', SettingValue)
from tb_Settings where SettingId = 23

declare @xml varchar(max);
select @xml = replace(convert(varchar(max),
(select 
	 'Pole Position Desktop' as 'Document/name'
	-- Is the mapicon filename correct?
	,(select
		'GPSPoleXmission' as '@id'
		,.75 as 'IconStyle/scale'
		,replace(@template, '{page}', 'GpsVisitXmissionStructure.aspx') as 'BalloonStyle/text'
		,Replace(@settingValue, '{0}', 'mapicon_visit.png') as 'IconStyle/Icon/href'
		for xml path('Style'), type) as 'Document'
	
		,(select 
			-- what test shold show up on the map?
			List.Value as 'name'

			-- all assets of this type get the same base style
			,'#GPSPoleXmission' as 'styleUrl'

			-- should we show a special icon?
			--,@TransmissionGpsVisitsIcon as 'Style/IconStyle/Icon/href'

			-- should we show it in a special color?
			--,@TransmissionGpsVisitsColor as 'Style/IconStyle/color'

			,'ID' as 'ExtendedData/Data/@name'
			,List.Value as 'ExtendedData/Data/value'

			-- where is it?
			,Convert(varchar, Longitude, 128) + ',' + Convert(varchar, Latitude, 128) + ',0' as 'Point/coordinates'
		from
			(select * from dbo.fn_Split(@TransmissionGpsVisitsList, default)) as List
			join tb_Vendor_Visit_XMissionStructures_Poles as Poles
				on Poles.Vendor_Visit_XMissionStructures_PoleId = Convert(int, List.Value)
			left join tb_XMissionStructures_TopTypes TopTypes
				on TopTypes.XMissionStructures_TopTypeId = Poles.XMissionStructures_PoleTopTypeFk
		for xml path('Placemark'), TYPE) as 'Document'	

for xml path('kml'))), '<kml>', '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.2">')

select @xml;

 